import moment from 'moment';
import {
  getActivityTime,
} from '/common/api';

/**
 * randomInt 随机数
 * @param {number} min 最小值
 * @param {number} max 最大值
 */
export function randomInt(min,max) {
  return Math.floor(Math.random()*(max - min + 1) + min);
}

/**
 * getTimeList 获取时间列表
 */
export function getTimeList() {
  return new Promise((resolve, reject) => {
    getActivityTime().then((res) => {
      const { data } = res;
      if (data.success) {
        const { activityTimeList } = data.data;
        const timeList = {};
        activityTimeList.forEach((value) => {
          const { activityTime } = value;
          const time = moment(activityTime, 'YYYY-MM-DD H:mm:ss');
          if (timeList[time.format('M月DD日')]) {
            timeList[time.format('M月DD日')].push(time.format('HH:mm'));
          } else {
            timeList[time.format('M月DD日')] = [time.format('HH:mm')];
          }
        });
        resolve(timeList);
      } else {
        reject(res);
      }
    }).catch((err) => {
      console.log(err);
    });
  });
}

/**
 * getRouletteStatus 获取当前时间&抽奖状态
 */
export function getRouletteStatus(duration) {
  return new Promise((resolve, reject) => {
    getActivityTime().then((res) => {
      const { data } = res;
      if (data.success) {
        const { activityTimeList, currentTime } = data.data;
        let status = '',
            nextTime = 0,
            activityTime = 0;
        const current = moment(currentTime, 'YYYY-MM-DD H:mm:ss');
        for (let i = 0; i < activityTimeList.length; i++) {
          const currentTime = current.valueOf();
          const startTime = moment(activityTimeList[i].activityTime, 'YYYY-MM-DD H:mm:ss').valueOf();
          const endTime = moment(activityTimeList[i].activityTime, 'YYYY-MM-DD H:mm:ss').add(duration, 'm').valueOf();
          if (currentTime < startTime) {
            status = 'pause';
            nextTime = startTime;
            break;
          } else if (currentTime >= startTime && currentTime < endTime) {
            status = 'start';
            activityTime = startTime;
            if (i < activityTimeList.length - 1) {
              nextTime = moment(activityTimeList[i + 1].activityTime, 'YYYY-MM-DD H:mm:ss').valueOf(); 
            }
            break;
          } else if (currentTime > endTime) {
            if (i >= activityTimeList.length - 1) {
              status = 'end';
            }
          }
        }
        resolve({
          current: current.valueOf(),
          status,
          nextTime,
          activityTime,
        });
      } else {
        reject(res);
      }
    }).catch((err) => {
      console.log(err);
    });
  });
}

/**
 * timeListener 倒计时
 */
export const timeListener = (function() {
  let timeCounter = null;
  return function(refresh, current, nextTime, clear) {
    if (clear && timeCounter) {
      clearTimeout(timeCounter);
      return;
    }
    const interval = 1000;
    const startTime = new Date().getTime();
    let ms = nextTime - current;
    let count = 0;
    if (ms >= 0) {
      if (timeCounter) clearTimeout(timeCounter);
      timeCounter = setTimeout(function countDownStart() {
        count++;
        var offset = new Date().getTime() - (startTime + count * interval);
        var nextTime = interval - offset;
        if (nextTime < 0) { nextTime = 0 };
        ms -= interval;
        if (ms < 0) {
          clearTimeout(timeCounter);
          refresh();
        } else {
          timeCounter = setTimeout(countDownStart,nextTime);
        }
      }, interval);
    }
  }
})();

/**
 * request 接口请求公共部分
 * @param {Object} params 请求参数
 */
export function request(params) {
  const { url, headers } = params;
  return new Promise((resolve, reject) => {
    my.httpRequest({
      url,
      headers: {
        'Content-Type': 'application/json;charset=UTF-8',
        ...headers,
      },
      success: (res) => {
        resolve(res);
      },
      fail: (res) => {
        reject(res);
      }
    });
  });
}

/**
 * saveUserInfo 保存用户信息到sessionStorage
 * @param {Object} res 用户信息响应数据
 */
export function saveUserInfo(res) {
  const { accessToken, userId } = res.data.data;
  if ( accessToken && userId ) {
    my.setStorageSync({
      key: 'accessToken',
      data: accessToken,
    });
    my.setStorageSync({
      key: 'userId',
      data: userId,
    })
  } 
}

/**
 * getSessionStorage 从sessionStorage获取用户信息
 */
export function getSessionStorage() {
  const accessToken = my.getStorageSync({
    key: 'accessToken',
  }).data;
  const userId = my.getStorageSync({
    key: 'userId',
  }).data;
  return {
    accessToken,
    userId,
  }
}